<template>
  <div v-loading="loading" class="parentStyle">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <div class="area-header">
        <span class="area-header-title">{{ $t('项目基本信息') }}</span>
      </div>
      <el-row>
        <el-col :span="12" :style="{height: Wheight}">
          <el-form-item :label="$t('项目名称')" prop="dealName">
            <el-input v-if="!form.id" v-model="form.dealName" :placeholder="$t('项目名称')" show-word-limit :maxlength="100" @change="checkDealNameExist()" />
            <el-input v-else v-model="form.dealName" show-word-limit :maxlength="100" @change="checkDealNameExist()">
              <template v-if="form.id" slot="append">
                <span @click="chartOpenHandle">{{ $t('查看投资架构图') }}</span>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('投资形式')" prop="dealBaseProperty.investmentType">
            <dictSelect
              v-model="form.dealBaseProperty.investmentType"
              dictionary="deal_base_investment_form"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('是否关联交易')" prop="dealBaseProperty.relatedTransaction">
            <el-radio-group v-model="form.dealBaseProperty.relatedTransaction">
              <el-radio :label="'Y'">{{ $t('是') }}</el-radio>
              <el-radio :label="'N'">{{ $t('否') }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col v-if="form.dealBaseProperty.relatedTransaction === 'Y'" :span="12">
          <el-form-item :label="$t('关联方')" prop="dealBaseProperty.relatedParty">
            <el-input v-model="form.dealBaseProperty.relatedParty" :placeholder="$t('关联方')" show-word-limit :maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('项目负责人')" prop="personCharge">
            <UserSelect
              v-model="form.personCharge"
              :placeholder="$t('项目负责人')"
              @change="personChargeChange($event)"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('项目用途')" prop="dealBaseProperty.investmentPurpose">
            <dictSelect
              v-model="form.dealBaseProperty.investmentPurpose"
              dictionary="deal_base_project_purpose"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('项目类型')" prop="dealType">
            <dictSelect
              v-model="form.dealType"
              :disabled="(form.dealType !== undefined && form.id !== undefined) || !dealTypeUpdate"
              dictionary="deal_type"
              @change="dealTypeChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('项目状态')" prop="dealStatus">
            <dictSelect
              v-model="form.dealStatus"
              dictionary="deal_status"
              :disabled="dealStatusModify"
              @change="dealStatusChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('投资币种')" prop="currency">
            <el-select v-model="form.currency" :placeholder="$t('投资币种')">
              <el-option
                v-for="dict in currencyOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('项目来源')" prop="dealSource">
            <el-input v-model="form.dealSource" :placeholder="$t('项目来源')" show-word-limit :maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('关注等级')" prop="levelConcern">
            <el-select v-model="form.levelConcern" :placeholder="$t('关注等级')" clearable>
              <el-option
                v-for="dict in levelConcernOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('初次接触时间')" prop="dateTouchFirst">
            <DatePicker v-model="form.dateTouchFirst" :placeholder="$t('初次接触时间')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('预计投资时间')" prop="dateInvestmentEstimate">
            <DatePicker v-model="form.dateInvestmentEstimate" :placeholder="$t('预计投资时间')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('预计投资金额') + $t('金额单位')" prop="amountInvestmentEstimate">
            <Money v-model="form.amountInvestmentEstimate" unit="w" :placeholder="$t('预计投资金额')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('预计收益率(%)')" prop="expectedRate">
            <money v-model="form.dealBaseProperty.expectedRate" unit="rate" :placeholder="$t('预计收益率%')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('推荐人')" prop="sourceName">
            <el-input v-model="form.sourceName" :placeholder="$t('推荐人')" show-word-limit :maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('项目简介')" prop="dealIntroduction">
            <el-input v-model="form.dealIntroduction" type="textarea" :placeholder="$t('项目简介')" show-word-limit :maxlength="2000" />
          </el-form-item>
        </el-col>
        <el-col v-if="form.dealStatus ==='ZZ'" :span="24">
          <el-form-item :label="$t('终止原因')" prop="terminationReason">
            <el-input v-model="form.terminationReason" type="textarea" :placeholder="$t('终止原因')" show-word-limit :maxlength="2000" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('运营模式')" prop="dealBaseProperty.operationMode">
            <el-input v-model="form.dealBaseProperty.operationMode" type="textarea" :placeholder="$t('运营模式')" show-word-limit :maxlength="2000" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('备注')" prop="remark">
            <el-input v-model="form.remark" type="textarea" :placeholder="$t('备注')" show-word-limit :maxlength="2000" />
          </el-form-item>
        </el-col>
      </el-row>
      <div v-if="form.dealBaseProperty.investmentType === 'GQJY'">
        <!-- ------------------------------------------------   项目公司信息   ----------------------------- -->
        <div class="area-header" style="margin-top: 15px;">
          <span class="area-header-title">{{ $t('项目公司信息') }}</span>
        </div>
        <div>
          <el-row>
            <el-col :span="12" :style="{height: Wheight}">
              <el-form-item prop="company.companyName">
                <span slot="label"> {{ $t(companyLabel) }} </span>
                <el-autocomplete
                  v-model="form.company.companyName"
                  class="inline-input"
                  :fetch-suggestions="companyQuerySearch"
                  :placeholder="$t(companyLabel)"
                  :trigger-on-focus="false"
                  :maxlength="100"
                  @select="companyHandleSelect"
                >
                  <template v-if="form.id" slot="append" @click="companyHandleSelect">
                    <router-link
                      target="_blank"
                      :to="{path:'/company/base/companyBaseHome',query:{companyId:form.companyId}}"
                      class="link_a"
                    >{{ $t('查看标的公司信息') }}</router-link>
                  </template>
                </el-autocomplete>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('拟持股比例') + $t('(%)')" prop="company.proposedShareholdingRatio">
                <Money v-model="form.company.proposedShareholdingRatio" unit="rate" :placeholder="$t('拟持股比例%')" />
              </el-form-item>
            </el-col>
            <Area ref="cityZj" :buss-data="form.company" :prop-city="'company.cityRegistered'" :prop-s-f="'company.provinceRegistered'" :prop-district="'company.districtRegistered'" />
            <el-col :span="12">
              <el-form-item :label="$t('注册资本') + $t('金额单位')" prop="company.capitalRegistered">
                <Money v-model="form.company.capitalRegistered" unit="w" :placeholder="$t('注册资本') + $t('金额单位')" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('成立日期') " prop="company.setDate">
                <DatePicker v-model="form.company.setDate" :placeholder="$t('成立日期')" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('统一信用码') " prop="company.creditCode">
                <el-input v-model="form.company.creditCode" :placeholder="$t('统一信用码')" show-word-limit maxlength="100" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item :label="$t('注册地址') " prop="company.detailsRegistered">
                <el-input v-model="form.company.detailsRegistered" :placeholder="$t('注册地址')" show-word-limit maxlength="200" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <!-- ------------------------------------------------   项目公司信息   end ----------------------------- -->
        <!-- ------------------------------------------------   物业信息   ----------------------------- -->
        <div class="area-header" style="margin-top: 15px;">
          <span class="area-header-title">{{ $t('物业信息') }}</span>
        </div>
        <div>
          <el-row>
            <!-- 24: 物业名称 -->
            <el-col :span="24">
              <el-form-item :label="$t('物业名称') " prop="dealBaseProperty.propertyName">
                <el-input v-model="form.dealBaseProperty.propertyName" :placeholder="$t('物业名称')" maxlength="200" />
              </el-form-item>
            </el-col>
            <!-- 省市 -->
            <Area ref="cityZj" :buss-data="form.dealBaseProperty" :prop-s-f="'dealBaseProperty.provinceRegistered'" :prop-city="'dealBaseProperty.cityRegistered'" :prop-district="'dealBaseProperty.districtRegistered'" />
            <!-- 24: 详细地址 -->
            <el-col :span="24">
              <el-form-item :label="$t('详细地址') " prop="dealBaseProperty.address">
                <el-input v-model="form.dealBaseProperty.address" :placeholder="$t('详细地址')" show-word-limit maxlength="200" />
              </el-form-item>
            </el-col>
            <!-- 12: 物业类型 下拉 -->
            <el-col :span="12">
              <el-form-item :label="$t('物业类型')" prop="dealBaseProperty.investmentForm">
                <dictSelect v-model="form.dealBaseProperty.investmentForm" dictionary="deal_base_investmentForm" :placeholder="$t('请选择')" />
              </el-form-item>
            </el-col>
            <!-- 12: 账面价值 number-->
            <el-col :span="12">
              <el-form-item :label="$t('账面价值') + $t('金额单位')" prop="dealBaseProperty.bookValue">
                <Money v-model="form.dealBaseProperty.bookValue" unit="w" :placeholder="$t('账面价值')" />
              </el-form-item>
            </el-col>
            <!-- 12: 总建筑面积(m2) number-->
            <el-col :span="12">
              <el-form-item :label="$t('总建筑面积') + $t('(m2)')" prop="dealBaseProperty.totalSurfaceArea">
                <Money v-model="form.dealBaseProperty.totalSurfaceArea" unit="y" :placeholder="$t('总建筑面积(m2)')" />
              </el-form-item>
            </el-col>
            <!-- 12: 可出租面积(m2) number-->
            <el-col :span="12">
              <el-form-item :label="$t('可出租面积') + $t('(m2)')" prop="dealBaseProperty.rentableArea">
                <Money v-model="form.dealBaseProperty.rentableArea" unit="y" :placeholder="$t('可出租面积(m2)')" />
              </el-form-item>
            </el-col>
            <!-- 12: 当前出租率(%) number-->
            <el-col :span="12">
              <el-form-item :label="$t('当前出租率') + $t('(%)')" prop="dealBaseProperty.currentOccupancyRates">
                <Money v-model="form.dealBaseProperty.currentOccupancyRates" unit="rate" :placeholder="$t('当前出租率%')" />
              </el-form-item>
            </el-col>
            <!-- 12: 当前租金单价(元/m2/天) number-->
            <el-col :span="12">
              <el-form-item :label="$t('当前租金单价') + $t('(元/m2/天)')" prop="dealBaseProperty.currentRentalUnitPrice">
                <Money v-model="form.dealBaseProperty.currentRentalUnitPrice" unit="y" :placeholder="$t('当前租金单价(元/m2/天)')" />
              </el-form-item>
            </el-col>
            <!-- 12: 总层数 number-->
            <el-col :span="12">
              <el-form-item :label="$t('总层数')" prop="dealBaseProperty.totalFloors">
                <Money v-model="form.dealBaseProperty.totalFloors" unit="y" :placeholder="$t('总层数')" />
              </el-form-item>
            </el-col>
            <!-- 12: 是否存在抵押等权利限制 单选 -->
            <el-col :span="12">
              <el-form-item :label="$t('是否存在抵押等权利限制')" prop="dealBaseProperty.restrictionOfRights">
                <el-radio-group v-model="form.dealBaseProperty.restrictionOfRights">
                  <el-radio :label="'Y'">{{ $t('是') }}</el-radio>
                  <el-radio :label="'N'">{{ $t('否') }}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <!-- 12: 竣工日期: 时间 -->
            <el-col :span="12">
              <el-form-item :label="$t('竣工日期') " prop="dealBaseProperty.completionDate">
                <DatePicker v-model="form.dealBaseProperty.completionDate" :placeholder="$t('竣工日期')" />
              </el-form-item>
            </el-col>
            <!-- 12: 交付日期: 时间 -->
            <el-col :span="12">
              <el-form-item :label="$t('交付日期') " prop="dealBaseProperty.deliveryDate">
                <DatePicker v-model="form.dealBaseProperty.deliveryDate" :placeholder="$t('交付日期')" />
              </el-form-item>
            </el-col>
            <!-- 12: 土地使用编号  input -->
            <el-col :span="12">
              <el-form-item :label="$t('土地使用编号') " prop="dealBaseProperty.landUseNumber">
                <el-input v-model="form.dealBaseProperty.landUseNumber" :placeholder="$t('土地使用编号')" maxlength="100" />
              </el-form-item>
            </el-col>
            <!-- 12: 土地出让方式  下拉 -->
            <el-col :span="12">
              <el-form-item :label="$t('土地出让方式')" prop="dealBaseProperty.landTransferMethod">
                <dictSelect v-model="form.dealBaseProperty.landTransferMethod" dictionary="deal_base_landTransferMethod" :placeholder="$t('请选择')" />
              </el-form-item>
            </el-col>
            <!-- 12: 土地使用获得时间  时间 -->
            <el-col :span="12">
              <el-form-item :label="$t('土地使用获得时间') " prop="dealBaseProperty.landUseAcquisitionTime">
                <DatePicker v-model="form.dealBaseProperty.landUseAcquisitionTime" :placeholder="$t('土地使用获得时间')" />
              </el-form-item>
            </el-col>
            <!-- 12:使用期限  input -->
            <el-col :span="12">
              <el-form-item :label="$t('使用期限') " prop="dealBaseProperty.periodOfUse">
                <el-input v-model="form.dealBaseProperty.periodOfUse" :placeholder="$t('使用期限')" show-word-limit maxlength="100" />
              </el-form-item>
            </el-col>
            <!-- 24: 备注 -->
            <el-form-item :label="$t('备注')" prop="dealBaseProperty.remark">
              <el-input v-model="form.dealBaseProperty.remark" type="textarea" :placeholder="$t('备注')" show-word-limit :maxlength="2000" />
            </el-form-item>
          </el-row>
        </div>
      </div>
      <!-- ------------------------------------------------   物业信息  end ----------------------------- -->
      <!-- 团队成员 -->
      <div v-if="form.id === undefined" class="area-header" style="margin-top: 15px;">
        <span class="area-header-title">{{ $t('团队成员') }}</span>
      </div>
      <div v-if="form.id === undefined" style="margin-top:15px;">
        <el-table :data="form.dealTeamList" border class="nowrapTable formTable">
          <el-table-column :label="$t('序号')" align="center" width="50">
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column :label="$t('用户名称')" align="center">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('用户名称') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'dealTeamList.' + scope.$index + '.user.userId'" :rules="dealTeamListRules.userId">
                <UserSelect v-model="scope.row.user.userId" :disabled="scope.row.disabled" :placeholder="$t('选择用户')" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('参与角色')" align="center">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('参与角色') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'dealTeamList.' + scope.$index + '.role'" :rules="dealTeamListRules.role">
                <el-select v-model="scope.row.role" :disabled="scope.row.disabled && scope.row.role === 'F'" :placeholder="$t('参与角色')">
                  <el-option
                    v-for="dict in roleOptions"
                    :key="dict.dictValue"
                    :label="$t(dict.dictLabel)"
                    :value="dict.dictValue"
                    :disabled="dict.dictValue === 'F' || dict.dictLabel === '项目负责人'"
                  />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('备注')" align="center">
            <template slot="header" slot-scope="{}">
              <span>{{ $t('备注') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'dealTeamList.' + scope.$index + '.remark'">
                <el-input v-model="scope.row.remark" type="textarea" maxlength="2000" class="fileTextarea" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column v-if="!btnHide" :label="$t('操作')" align="center" width="60px">
            <template slot-scope="scope">
              <el-button v-hasPermi="['deal:dealbase:edit']" :disabled="scope.row.disabled" size="small" type="text" icon="el-icon-delete" @click="delTeam(scope.$index)" />
            </template>
          </el-table-column>
        </el-table>
        <div v-if="!btnHide" class="tol">
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="addTeam()">{{ $t("添加") }}</el-button>
        </div>
      </div>
      <!-- 附件列表 -->
      <FileTable :list.sync="form.fileList" has-permi="deal:dealbase" data-type="deal_base" :business-type="form.dealType" :select-business-data="false" />
    </el-form>
    <div v-show="!btnHide" slot="footer" class="dialog-footer">
      <SaveBtn has-permi="deal:dealbase" :cancel-show="openLocation === undefined" :bus-data="form" :cache-key="'deal_base_' + form.dealType" @cancelCustom="cancelCustom" />
    </div>
    <el-dialog :title="$t('')" :visible.sync="chartOpen" :close-on-click-modal="false" :lock-scroll="false" custom-class="dialogForm" append-to-body>
      <invest-structure-chart ref="investStructureChart" :chart-data="chartData" :btn-list="btnList" />
    </el-dialog>
  </div>
</template>

<script>
import Area from '@/components/Area'
import investStructureChart from './investStructureChart'
import { saveDealBase, getDealBase, getDealBaseByName } from '@/api/base/deal/dealBase'
import { companyListByName, companyDetailsByName } from '@/api/company/base/companyBase'
import { investChartData } from '@/api/fund/fundBase'
import { saveDealInvestment } from '@/api/deal/investment/dealInvestment'
export default {
  components: {
    Area,
    investStructureChart
  },
  data() {
    return {
      loading: false,
      Wheight: '83px',
      // 公司名称label
      companyLabel: '公司名称',
      // 项目类型是否可以修改
      dealTypeUpdate: true,
      // 表单参数
      form: {
        company: {},
        dealBaseProperty: {}
      },
      // 项目状态是否可以修改
      dealStatusModify: false,
      // 是否隐藏保存等按钮
      btnHide: false,
      // 打开页面的位置，如果是通过项目home页面的路由打开，保存时不调用刷新list页面的方法
      openLocation: undefined,
      // 表单校验
      rules: {
        investmentType: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        dealName: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        dealType: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        personCharge: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        dealSource: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        dealStatus: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        terminationReason: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        currency: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        'company.companyName': [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        'company.proposedShareholdingRatio': [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        'company.capitalRegistered': [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        'company.setDate': [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        'company.creditCode': [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        'company.detailsRegistered': [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        'company.cityRegistered': [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        'company.provinceRegistered': [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        'dealBaseProperty.cityRegistered': [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        'dealBaseProperty.provinceRegistered': [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        'dealBaseProperty.investmentForm': [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        'dealBaseProperty.expectedRate': [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        'dealBaseProperty.relatedTransaction': [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        'dealBaseProperty.investmentPurpose': [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        'dealBaseProperty.relatedParty': [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        'dealBaseProperty.propertyName': [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        'dealBaseProperty.address': [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        'dealBaseProperty.bookValue': [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        'dealBaseProperty.totalSurfaceArea': [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        'dealBaseProperty.rentableArea': [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        'dealBaseProperty.currentOccupancyRates': [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        'dealBaseProperty.currentRentalUnitPrice': [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        'dealBaseProperty.totalFloors': [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        'dealBaseProperty.restrictionOfRights': [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        'dealBaseProperty.completionDate': [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        'dealBaseProperty.deliveryDate': [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        'dealBaseProperty.landUseNumber': [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        'dealBaseProperty.landTransferMethod': [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        'dealBaseProperty.landUseAcquisitionTime': [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        'dealBaseProperty.periodOfUse': [{ required: true, message: this.$t('必填信息'), trigger: 'change' }]
      },
      dealTeamListRules: {
        userId: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        role: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }]
      },
      // 币种
      currencyOptions: [],
      // 项目类型
      dealTypeOptions: [],
      // 项目来源
      dealSourceOptions: [],
      // 关注等级
      levelConcernOptions: [],
      // 项目ID
      dealId: this.$route.query.id,
      // 天眼查查询条件
      tycParam: {
        id: '',
        companyName: '',
        tycId: ''
      },
      chartOpen: false,
      chartData: {},
      // 参与角色 字典deal_team_role字典
      roleOptions: [],
      btnList: [
        {
          name: '出资人',
          type: 'investor',
          color: 'rgba(183,221,232)'
        },
        {
          name: 'GP',
          type: 'gp',
          color: 'rgba(254,229,153)'
        },
        {
          name: '投资主体',
          type: 'fund',
          color: 'rgba(221,214,229)'
        },
        {
          name: 'SPV',
          type: 'spv',
          color: 'rgba(215,227,191)'
        },
        {
          name: '项目',
          type: 'deal',
          color: 'rgba(216,216,216)'
        }
      ]
    }
  },
  watch: {
  },
  mounted() {
    this.$bus.$emit('async_done')
  },
  created() {
  },
  methods: {
    dealTypeChange(val) {
      if (val === 'equity') {
        this.companyLabel = '公司名称'
      } else if (val === 'debt') {
        this.companyLabel = '融资方名称'
      } else if (val === 'bf') {
        this.companyLabel = '基金名称'
      } else if (val === 'estate') {
        this.companyLabel = '项目公司'
      } else if (val === 'property') {
        this.companyLabel = '项目公司名称'
      }
      this.$forceUpdate()
    },
    // 项目状态变更
    dealStatusChange(val) {
      if (val === 'CB') {
        this.rules.personCharge = null
      } else {
        this.rules.personCharge = [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
      }
    },
    // 初始化数据
    async init(data) {
      this.loading = true
      await Promise.all(this.getDictOptions())
      if (data !== undefined && data !== null && data.id !== null && data.id !== '' && data.id !== undefined) {
        this.loading = true
        // this.reset()
        getDealBase(data.id).then(response => {
          this.form = response.data
          this.$nextTick(() => {
            if (this.$refs.cityZj?.initCity !== undefined) {
              this.$refs.cityZj.initCity()
            }
          })
          // 储备项目，项目负责人设置为非必填
          this.dealStatusChange(this.form.dealStatus)
          this.loading = false
        })
      } else {
        this.reset(data)
        this.addTeamPerson()
        this.loading = false
      }
    },
    // 表单重置
    reset(data) {
      console.log('重置表单')
      this.form = {
        id: undefined,
        dealName: undefined,
        dealNamePinyin: undefined,
        personCharge: this.$store.state.user.userId,
        dealSource: undefined,
        dateTouchFirst: undefined,
        dateInvestmentEstimate: undefined,
        amountInvestmentEstimate: undefined,
        currency: 'CNY',
        levelConcern: undefined,
        dealIntroduction: undefined,
        dealStrongPoint: undefined,
        dealScruple: undefined,
        dealStatus: undefined,
        companyURL: undefined,
        transactionDetails: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        remark: undefined,
        delFlag: undefined,
        company: {
          companyName: '',
          companyShortName: undefined,
          industryFirst: undefined,
          industrySecond: undefined,
          proposedShareholdingRatio: 100,
          provinceRegistered: undefined,
          cityRegistered: undefined,
          capitalRegistered: undefined,
          setDate: undefined,
          creditCode: undefined,
          detailsRegistered: undefined,
          districtRegistered: undefined
        },
        dealBaseProperty: {
          investmentForm: undefined,
          relatedTransaction: 'Y',
          relatedParty: undefined,
          investmentPurpose: undefined,
          propertyName: undefined,
          cityRegistered: undefined,
          provinceRegistered: undefined,
          address: undefined,
          bookValue: undefined,
          totalSurfaceArea: undefined,
          rentableArea: undefined,
          currentOccupancyRates: undefined,
          currentRentalUnitPrice: undefined,
          totalFloors: undefined,
          restrictionOfRights: undefined,
          completionDate: undefined,
          deliveryDate: undefined,
          landUseNumber: undefined,
          landTransferMethod: undefined,
          landUseAcquisitionTime: undefined,
          periodOfUse: undefined
        },
        fileList: []
      }
      if (data !== undefined && data != null) {
        if (data.dealStatus !== undefined) {
          this.dealStatusModify = true
          this.form.dealStatus = data.dealStatus
          // 储备项目，项目负责人设置为非必填
          this.dealStatusChange(this.form.dealStatus)
        }
        if (data.dealType !== undefined) {
          this.dealTypeUpdate = false
          this.form.dealType = data.dealType
        }
      }
      this.resetForm('form')
    },
    // 关闭form页面
    closeForm() {
      // 关闭form页面遮罩层
      this.loading = false
      // 关闭form页面
      if (this.$parent.$parent.formPropertyOpen !== undefined) {
        this.$parent.$parent.formPropertyOpen = false
      }
      // 刷新list页面
      if (this.$parent.$parent.getList !== undefined) {
        this.$parent.$parent.getList()
      }
      if (this.$parent.$parent.getViewList !== undefined) {
        this.$parent.$parent.getViewList()
      }
    },
    // 校验数据必填等信息
    validateData: function() {
      return new Promise((resolve, reject) => {
        this.$refs['form'].validate(validTop => {
          if (validTop) {
            resolve()
          } else {
            reject()
            this.locationError(document)
          }
        })
      })
    },
    /** 提交按钮bottom */
    submitForm: function() {
      return new Promise((resolve, reject) => {
        this.validateData().then(() => {
          this.loading = true
          saveDealBase(this.form).then(response => {
            if (response.code === 200) {
              // 如果在母基金页面新建的项目, 则给这个新建的项目添加一个当前母基金的出资人
              if (this.$route.query.fundType === 'fof') {
                const dealInvestor = {
                  dealId: response.data.id,
                  investorId: this.$route.query.id,
                  investorType: 'fund',
                  currency: this.form.currency ? this.form.currency : 'CNY',
                  dateInvestmentEstimate: new Date(),
                  amountInvestmentEstimate: 0
                }
                saveDealInvestment(dealInvestor).then(() => {
                  this.closeForm()
                })
              }
              // 如果是通过项目home页面的路由打开，保存时不调用刷新list页面的方法
              if (this.openLocation === 'Home') {
                // 项目里边保存
                this.loading = false
              }
              if (this.$parent.$parent.$parent?.formProperty !== undefined) {
                this.$parent.$parent.$parent.formProperty = false
                this.$parent.$parent.$parent.init()
              }
              this.msgSuccess(this.$t('保存成功'))
              this.closeForm()
              resolve()
            } else {
              this.msgError(response.msg)
              this.loading = false
              reject()
            }
          }).catch(() => {
            this.loading = false
          })
        }).catch(() => {
          reject()
        })
      })
    },
    // 标的公司查询
    companyQuerySearch(queryString, cb) {
      companyListByName(queryString).then(res => {
        if (res.code === 200) {
          cb(res.data)
        }
      })
    },
    // 标的公司选择后事件
    companyHandleSelect(item) {
      this.form.company.tycId = item.id
      this.checkDealNameExist()
      this.fectchDataSelect(item)
    },
    // 判断项目名称是否存在
    checkDealNameExist() {
      const dealName = this.form.dealName
      if (dealName === '' || dealName === undefined) {
        this.rules.dealName = [{ required: true, message: this.$t('必填信息'), trigger: 'change' }]
        return
      }
      this.tycParam.dealName = dealName

      getDealBaseByName(this.tycParam).then(res => {
        if (res.data !== null && res.data.id !== this.form.id) {
          this.rules.dealName = [{ required: true, message: this.$t('项目名称不能重复'), trigger: 'change' }]
          this.form.dealName = ''
        }
      })
    },
     // 标的公司选择后事件
      fectchDataSelect(item) {
            this.tycParam.id = this.form.id
            this.tycParam.tycId = item.id
            this.tycParam.companyName = item.name
            this.tycParam.orgType = item.type
            this.orgTypeCompany = item.type
            companyDetailsByName(this.tycParam).then(res => {
                // 公司简称
                this.form.company.companyShortName = res.data.companyShortName
                // 公司名称
                this.form.company.companyName = res.data.companyName
                // 企业统一社会信用代码
                this.form.company.creditCode = res.data.creditCode
                // 法人代表
                this.form.company.legalPerson = res.data.legalPerson
                // 成立时间
                this.form.company.setDate = res.data.setDate
                // 一级行业
                this.form.company.industryFirst = res.data.industryFirst
                this.form.company.industrySecond = res.data.industrySecond
                this.$refs.industryZj.initIndustrySecond()
                // 注册地-省
                this.form.company.provinceRegistered = res.data.provinceRegistered
                // 注册市
                this.form.company.cityRegistered = res.data.cityRegistered
                this.$refs.cityZj.initCity()
                this.$refs.cityZj.initDistrict()
                 // 注册区
                this.form.company.districtRegistered = res.data.registerDistrict
                // 注册地-详细地址
                this.form.company.detailsRegistered = res.data.detailsRegistered
                // 注册资本金额
                this.form.company.capitalRegistered = res.data.capitalRegistered
                // 注册资本币种
                this.form.company.currency = res.data.currency
                // 经营范围
                this.form.company.businessScope = res.data.businessScope
                // 天眼查ID
                this.form.company.tycId = res.data.tycId
                // 公司logo
                this.form.company.logoInfo = res.data.logoInfo
                // 企业简介
                this.form.company.remark = res.data.remark
                // 实收资本
                this.form.company.actualCapital = res.data.actualCapital
                // 实收资本币种
                 this.form.actualCurrency = res.data.actualCurrency
                 this.$forceUpdate()
                this.msgSuccess(this.$t('已获取工商信息！'))
              })
          },
    getDictOptions() {
      return [
        // 币种
        this.getDicts('currency').then(response => {
          this.currencyOptions = response.data
        }),
        // 项目类型
        this.getDicts('deal_type').then(response => {
          this.dealTypeOptions = response.data
        }),
        // 项目来源
        this.getDicts('deal_source').then(response => {
          this.dealSourceOptions = response.data
        }),
        // 关注等级
        this.getDicts('level_concern').then(response => {
          this.levelConcernOptions = response.data
        }),
        // 项目阶段
        this.getDicts('deal_stage').then(response => {
          this.dealStageOptions = response.data
        }),
        // 团队成员字典
        this.getDicts('deal_team_role').then(response => {
          this.roleOptions = response.data
        })
      ]
    },
    chartOpenHandle() {
      this.chartOpen = true
      investChartData(this.form.id).then(res => {
        this.chartData = res.data
      })
      this.$nextTick(() => {
        this.$refs.investStructureChart.initCompany({ busId: this.form.company.id, busType: 'company', busName: this.form.company.companyName })
      })
    },
    personChargeChange(personCharge) {
      console.log('项目负责人change: ', personCharge)
      if (this.form) {
        if (personCharge === this.$store.state.user.userId) {
          if (this.form.dealTeamList !== undefined && this.form.dealTeamList !== null) {
            this.form.dealTeamList.forEach((item, index) => {
              if (item.disabled && item.role === 'F') {
                item.user.userId = personCharge
              }
              if (item.user.userId === personCharge && item.role !== 'F') {
                this.form.dealTeamList.splice(index, 1)
              }
            })
          }
        } else {
          // 如果项目负责人不是创建人本人, 修改默认添加的项目负责人, 并添加自己为项目成员
          if (this.form.dealTeamList !== undefined && this.form.dealTeamList !== null) {
            var isExist = false
            this.form.dealTeamList.forEach((item) => {
              if (item.disabled && item.role === 'F') {
                item.user.userId = personCharge
              }
              if (item.user.userId === this.$store.state.user.userId && !isExist) {
                isExist = true
              }
            })
            // 添加自己为项目成员
            if (!isExist) {
              this.addTeam({
                user: { userId: this.$store.state.user.userId },
                role: 'C',
                joinTime: new Date(),
                leave: 'N',
                disabled: true
              })
            }
          }
        }
      }
    },
    delTeam(index) {
      this.form.dealTeamList.splice(index, 1)
    },
    addTeamPerson() {
      this.addTeam({ user: { userId: this.$store.state.user.userId }, role: 'F', joinTime: new Date(), leave: 'N', disabled: true })
    },
    addTeam(data) {
      var row = {
        id: undefined,
        user: { userId: '' },
        role: 'C',
        joinTime: new Date(),
        leave: 'N',
        remark: undefined,
        disabled: false
      }
      if (data !== undefined) {
        row = data
      }
      if (!(this.form.dealTeamList instanceof Array)) {
        this.$set(this.form, 'dealTeamList', [])
      }
      this.$nextTick(() => {
        this.form.dealTeamList.push(row)
      })
    },
    cancelCustom() {
      this.$parent.$parent.formPropertyOpen = false
    }
  }
}
</script>

<style scoped>
.tianyan{
  border: 1px solid #DCDFE6;
  width: 17%;
  border-radius: 5px;
  height: 36px;
  float: right;
  text-align: right;
  padding-right: 15px;
  border-left: 0px;
  color: #1E9FFF;
  margin-top: -37px;
  font-size: 13px;
}
</style>
